<?php
// https://leetcode-cn.com/problems/longest-common-prefix/solution/zui-chang-gong-gong-qian-zhui-by-leetcode-solution/

// 依次遍历字符串数组中的每个字符串，对于每个遍历到的字符串，更新最长公共前缀，当遍历完所有的字符串以后，即可得到字符串数组中的最长公共前缀。

class Solution {

    /**
     * @param String[] $strs
     * @return String
     */
    function longestCommonPrefix($strs) {
        $str_number = count($strs);
        if ($str_number == 0) {
            return "";
        }
        if ($str_number == 1) {
            return $strs[0];
        }
        $prefix = $strs[0];
        for ($str_index = 1; $str_index < $str_number; $str_index++) {
            $prefix = $this->findCommonPrefix($prefix, $strs[$str_index]);
            if (strlen($prefix) == 0) {
                return "";
            }
        }
        return $prefix;
    }

    function findCommonPrefix($str1, $str2)
    {
        $min_str_len = min(strlen($str1), strlen($str2));
        $index = 0;
        while ($index < $min_str_len && $str1[$index] == $str2[$index]) {
            $index++;
        }
        return substr($str1, 0, $index);
    }
}

var_dump((new Solution())->longestCommonPrefix(["flower","flow","flight"]));